<template>
  <div class="item-types-management">
    <!-- 页面标题和操作栏 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h2 class="page-title mb-1">分类管理</h2>
        <p class="text-muted mb-0">管理商品类型，支持查看、编辑、删除等操作</p>
      </div>
      <div class="d-flex gap-2">
        <button class="btn btn-primary" @click="showAddItemTypeModal">
          <i class="bi bi-plus-circle me-2"></i>添加分类
        </button>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row g-3 align-items-end">
          <div class="col-md-4">
            <label class="form-label">所属版块</label>
            <select class="form-select" v-model="filters.categoryId" @change="loadItemTypes">
              <option value="">全部版块</option>
              <option v-for="category in categories" :key="category.id" :value="category.id">
                {{ category.name }}
              </option>
            </select>
          </div>
          <div class="col-md-4">
            <label class="form-label">关键词搜索</label>
            <div class="input-group">
              <span class="input-group-text">
                <i class="bi bi-search"></i>
              </span>
              <input 
                type="text" 
                class="form-control" 
                placeholder="搜索分类名称..."
                v-model="searchQuery"
                @input="handleSearch"
              >
            </div>
          </div>
          <div class="col-md-4">
            <button class="btn btn-outline-secondary w-100" @click="resetFilters">
              <i class="bi bi-arrow-clockwise me-2"></i>重置筛选
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分类列表 -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">分类列表</h5>
        <div class="d-flex align-items-center gap-2">
          <span class="text-muted small">共 {{ itemTypes.length }} 个分类</span>
        </div>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th width="50">ID</th>
                <th>分类名称</th>
                <th>所属版块</th>
                <th>分类描述</th>
                <th width="80">图标</th>
                <th>排序</th>
                <th>状态</th>
                <th>创建时间</th>
                <th width="120">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="itemType in itemTypes" :key="itemType.id">
                <td>{{ itemType.id }}</td>
                <td>
                  <strong class="text-primary">{{ itemType.name }}</strong>
                </td>
                <td>
                  <span class="badge bg-primary">{{ getCategoryName(itemType.categoryId) }}</span>
                </td>
                <td>
                  <span class="text-muted">{{ itemType.description || '暂无描述' }}</span>
                </td>
                <td>
                  <i v-if="itemType.icon" :class="itemType.icon" style="font-size: 1.5rem;"></i>
                  <span v-else class="text-muted">无图标</span>
                </td>
                <td>{{ itemType.sortOrder }}</td>
                <td>
                  <span class="badge" :class="itemType.status === 'active' ? 'bg-success' : 'bg-secondary'">
                    {{ itemType.status === 'active' ? '启用' : '停用' }}
                  </span>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <small class="text-muted">{{ formatDate(itemType.createdAt) }}</small>
                  </div>
                </td>
                <td>
                  <div class="btn-group btn-group-sm">
                    <button 
                      class="btn btn-outline-primary"
                      @click="editItemType(itemType)"
                      title="编辑"
                    >
                      <i class="bi bi-pencil"></i>
                    </button>
                    <button 
                      class="btn" 
                      :class="itemType.status === 'active' ? 'btn-outline-warning' : 'btn-outline-success'"
                      @click="toggleItemTypeStatus(itemType)"
                      :title="itemType.status === 'active' ? '停用分类' : '启用分类'"
                    >
                      <i class="bi" :class="itemType.status === 'active' ? 'bi-eye-slash' : 'bi-eye'"></i>
                    </button>
                    <button 
                      class="btn btn-outline-danger"
                      @click="deleteItemType(itemType)"
                      title="删除"
                    >
                      <i class="bi bi-trash"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 空状态 -->
        <div v-if="itemTypes.length === 0" class="text-center py-5">
          <i class="bi bi-tags display-1 text-muted"></i>
          <p class="text-muted mt-3">暂无分类数据</p>
        </div>
      </div>
    </div>

    <!-- 添加/编辑分类模态框 -->
    <div class="modal fade" id="itemTypeModal" tabindex="-1" aria-labelledby="itemTypeModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="itemTypeModalLabel">{{ isEditing ? '编辑分类' : '添加分类' }}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form>
              <div class="mb-3">
                <label for="categoryId" class="form-label">所属版块</label>
                <select class="form-select" id="categoryId" v-model="currentItemType.categoryId" required>
                  <option value="">请选择版块</option>
                  <option v-for="category in categories" :key="category.id" :value="category.id">
                    {{ category.name }}
                  </option>
                </select>
              </div>
              
              <div class="mb-3">
                <label for="name" class="form-label">分类名称</label>
                <input type="text" class="form-control" id="name" v-model="currentItemType.name" required>
              </div>
              
              <div class="mb-3">
                <label for="description" class="form-label">分类描述</label>
                <textarea class="form-control" id="description" v-model="currentItemType.description" rows="3"></textarea>
              </div>
              
              <div class="mb-3">
                <label for="icon" class="form-label">图标 </label>
                <input type="text" class="form-control" id="icon" v-model="currentItemType.icon" placeholder="例如: SVG代码">
                <div class="form-text">使用 阿里巴巴矢量图 SVG代码名，参考 <a href="https://www.iconfont.cn/" target="_blank">阿里巴巴矢量图</a></div>
              </div>
              
              <div class="mb-3">
                <label for="sortOrder" class="form-label">排序</label>
                <input type="number" class="form-control" id="sortOrder" v-model="currentItemType.sortOrder">
              </div>
              
              <div class="mb-3">
                <label for="status" class="form-label">状态</label>
                <select class="form-select" id="status" v-model="currentItemType.status">
                  <option value="active">启用</option>
                  <option value="inactive">停用</option>
                </select>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="saveItemType">保存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getItemTypesService,
  addItemTypeService,
  updateItemTypeService,
  deleteItemTypeService,
  updateItemTypeStatusService
} from '@/api/ItemType.js'
import { getCategoriesService } from '@/api/categories.js'

// 引入Bootstrap的Modal组件
import { Modal } from 'bootstrap'

// 响应式数据
const itemTypes = ref([])
const categories = ref([])
const searchQuery = ref('')
const isEditing = ref(false)

const currentItemType = reactive({
  id: null,
  categoryId: '',
  name: '',
  description: '',
  icon: '',
  sortOrder: 0,
  status: 'active'
})

// 筛选条件
const filters = reactive({
  categoryId: ''
})

// 方法
const loadItemTypes = async () => {
  try {
    const response = await getItemTypesService()
    if (response.code === 0) {
      // 应用筛选条件
      let filteredItemTypes = response.data
      
      // 版块筛选
      if (filters.categoryId) {
        filteredItemTypes = filteredItemTypes.filter(itemType => 
          itemType.categoryId == filters.categoryId)
      }
      
      // 关键字搜索
      if (searchQuery.value) {
        const keyword = searchQuery.value.toLowerCase()
        filteredItemTypes = filteredItemTypes.filter(itemType => 
          itemType.name.toLowerCase().includes(keyword))
      }
      
      itemTypes.value = filteredItemTypes
    } else {
      ElMessage.error('获取分类列表失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败: ' + error.message)
  }
}

const loadCategories = async () => {
  try {
    const response = await getCategoriesService()
    if (response.code === 0) {
      categories.value = response.data
    } else {
      ElMessage.error('获取版块列表失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取版块列表失败: ' + error.message)
  }
}

const showAddItemTypeModal = () => {
  // 重置表单
  isEditing.value = false
  currentItemType.id = null
  currentItemType.categoryId = ''
  currentItemType.name = ''
  currentItemType.description = ''
  currentItemType.icon = ''
  currentItemType.sortOrder = 0
  currentItemType.status = 'active'
  
  // 显示模态框
  const itemTypeModal = new Modal(document.getElementById('itemTypeModal'))
  itemTypeModal.show()
}

const editItemType = (itemType) => {
  // 设置编辑状态
  isEditing.value = true
  // 填充表单数据
  currentItemType.id = itemType.id
  currentItemType.categoryId = itemType.categoryId
  currentItemType.name = itemType.name
  currentItemType.description = itemType.description
  currentItemType.icon = itemType.icon
  currentItemType.sortOrder = itemType.sortOrder
  currentItemType.status = itemType.status
  
  // 显示模态框
  const itemTypeModal = new Modal(document.getElementById('itemTypeModal'))
  itemTypeModal.show()
}

const saveItemType = async () => {
  try {
    // 表单验证
    if (!currentItemType.categoryId) {
      ElMessage.warning('请选择所属版块')
      return
    }
    
    if (!currentItemType.name) {
      ElMessage.warning('请输入分类名称')
      return
    }
    
    let response
    if (isEditing.value) {
      // 更新分类
      response = await updateItemTypeService(currentItemType)
    } else {
      // 添加分类
      response = await addItemTypeService(currentItemType)
    }
    
    if (response.code === 0) {
      await loadItemTypes()
      // 关闭模态框
      const itemTypeModalEl = document.getElementById('itemTypeModal')
      const itemTypeModal = Modal.getInstance(itemTypeModalEl) || new Modal(itemTypeModalEl)
      itemTypeModal.hide()
      ElMessage.success(isEditing.value ? '分类更新成功' : '分类添加成功')
    } else {
      ElMessage.error(isEditing.value ? '分类更新失败: ' + response.msg : '分类添加失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error(isEditing.value ? '分类更新失败: ' + error.message : '分类添加失败: ' + error.message)
  }
}

const toggleItemTypeStatus = async (itemType) => {
  try {
    const newStatus = itemType.status === 'active' ? 'inactive' : 'active'
    const response = await updateItemTypeStatusService(itemType.id, newStatus)
    
    if (response.code === 0) {
      itemType.status = newStatus
      ElMessage.success(newStatus === 'active' ? '分类已启用' : '分类已停用')
    } else {
      ElMessage.error('更新分类状态失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('更新分类状态失败: ' + error.message)
  }
}

const deleteItemType = async (itemType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${itemType.name}" 吗？此操作不可逆！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteItemTypeService(itemType.id)
    if (response.code === 0) {
      await loadItemTypes()
      ElMessage.success('分类删除成功')
    } else {
      ElMessage.error('删除分类失败: ' + response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除分类失败: ' + error.message)
    }
  }
}

const getCategoryName = (categoryId) => {
  if (!categoryId) return '未分类'
  const category = categories.value.find(cat => cat.id === categoryId)
  return category ? category.name : '未分类'
}

const handleSearch = () => {
  loadItemTypes()
}

const resetFilters = () => {
  searchQuery.value = ''
  filters.categoryId = ''
  loadItemTypes()
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadItemTypes()
  loadCategories()
})
</script>

<style scoped>
.page-title {
  color: #2c3e50;
  font-weight: 600;
}

.table th {
  border-top: none;
  font-weight: 600;
  color: #6c757d;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.table-hover > tbody > tr:hover > td {
  background-color: #e3f2fd !important;
}

.table > tbody > tr {
  transition: background-color 0.2s ease;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-responsive {
    font-size: 0.875rem;
  }
  
  .btn-group-sm > .btn {
    padding: 0.25rem 0.5rem;
  }
}
</style>